package nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * @ClassName SocketChannelDemo
 * @Description TODO
 * @Author leejiliang
 * @DateTime 2021/8/26 14:52
 * @Version 1.0
 */
public class SocketChannelDemo {


    public static void main(String[] args) throws IOException {
        var socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 8080));

        while (!socketChannel.finishConnect()) {

        }

    }


    public void sendFile() throws IOException {
        var filePath = "";
        var file = new File(filePath);

        if (!file.exists()) {
            throw new FileNotFoundException("文件不存在");
        }

        var fileInputChannel = new FileInputStream(file).getChannel();
        var socketChannel = SocketChannel.open();
        var connect = socketChannel.connect(new InetSocketAddress("127.0.0.1", 8080));
        socketChannel.configureBlocking(false);
        while (!socketChannel.finishConnect()) {
            System.out.println("do something else");
        }
        var buffer = sendFileNameAndLength(filePath, file, socketChannel);
        sendContent(file, fileInputChannel, socketChannel, buffer);


    }

    /**
     * 发送文件名称和长度
     *
     * @param fileName      文件名
     * @param file          文件
     * @param socketChannel socketChannel输出channel
     */
    public ByteBuffer sendFileNameAndLength(String fileName, File file, SocketChannel socketChannel) throws IOException {
        var charset = Charset.forName("utf-8");
        var encode = charset.encode(fileName);
        var buffer = ByteBuffer.allocate(1024);

        buffer.putInt(encode.capacity());

        buffer.flip();
        socketChannel.write(buffer);

        buffer.clear();

        socketChannel.write(encode);

        buffer.putLong(file.length());
        buffer.flip();
        socketChannel.write(buffer);

        buffer.clear();

        return buffer;
    }

    public void sendContent(File file, FileChannel fileChannel, SocketChannel socketChannel, ByteBuffer buffer) throws IOException {
        while (fileChannel.read(buffer) != -1) {
            buffer.flip();
            socketChannel.write(buffer);
            buffer.clear();
        }
    }
}
